package serv

import (
	"erp/model"
	"erp/service"
	"erp/utils"
	"fmt"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// func UserCartGetCntCtrl(c *gin.Context) {
// 	userData, _ := c.Get("userData")
// 	cnt, _ := dbEngine.Table("f_shop_order_goods").Where("user_id=? and order_id=0", userData.(model.User).Id).Count()

// 	c.JSON(200, ApiList{
// 		Status: 200,
// 		Data: ApiDataListObj{
// 			Total: cnt,
// 		},
// 	})
// }

func UserCartIndexCtrl(c *gin.Context) {
	var rows []map[string]any

	userData, _ := c.Get("userData")

	param := GetJsonData(c)
	page := 1
	limit := 10

	if param == nil {
	} else {
		page = int(param["page"].(float64))
		limit = int(param["limit"].(float64))
	}

	dbEngine.Table("f_shop_order_goods").Cols("id, goods_id, goods_name, goods_img, buy_number, sku_name, goods_price, selected, create_time").Where("user_id=? and order_id=0", userData.(model.User).Id).Limit(limit, (page-1)*limit).Find(&rows)
	cnt, _ := dbEngine.Table("f_shop_order_goods").Where("user_id=? and order_id=0", userData.(model.User).Id).Count()
	if rows == nil {
		rows = []map[string]any{}
	}
	c.JSON(200, ApiList{
		Status: 200,
		Data: ApiDataListObj{
			Total:   cnt,
			PerPage: limit,
			Data:    rows,
		},
	})
}

func UserCartAddCtrl(c *gin.Context) {
	postData := GetJsonData(c)
	userData, _ := c.Get("userData")

	cols := utils.FArray{"id", "goods_id", "goods_name", "goods_img", "buy_number", "sku_name", "goods_price"}
	dbData := map[string]any{
		"user_id":     userData.(model.User).Id,
		"order_id":    0,
		"create_time": time.Now().Format("2006-01-02 15:04:05"),
	}

	for k, v := range postData {
		if cols.Search(k) != -1 && v != nil {
			dbData[k] = v
		}
	}

	goodsData := service.GetShopGoods(int(dbData["goods_id"].(float64)))

	if goodsData.BuyMax > 0 {
		sql := "select sum(buy_number) as buy_number_total from f_shop_order_goods where user_id=" + utils.Strval(userData.(model.User).Id) + " and goods_id=" + utils.Strval(dbData["goods_id"].(float64))
		rowData, _ := dbEngine.QueryInterface(sql)
		if int(rowData[0]["buy_number_total"].(float64)) >= goodsData.BuyMax {
			c.JSON(200, map[string]any{"status": 403, "msg": "已领取该物品，请到购物车或采购单中查看！"})
			return
		}
	}

	_, err := dbEngine.Table("f_shop_order_goods").Insert(dbData)
	msg := "添加成功"

	if err != nil {
		c.JSON(200, map[string]any{"status": 500, "msg": err.Error()})
	} else {
		c.JSON(200, map[string]any{"status": 200, "msg": msg})
	}
}

/**
 * URL:/user/cart/createOrder
 */
func UserCartCreateOrderCtrl(c *gin.Context) {
	param := GetJsonData(c)
	userData, _ := c.Get("userData")

	ids := []string{}
	for _, v := range param["order_goods"].([]interface{}) {
		ids = append(ids, utils.Strval(v))
	}

	var orderGoodsList []map[string]any
	dbEngine.Table("f_shop_order_goods").Cols("id, goods_id, goods_name, goods_img, buy_number, sku_name, goods_price, selected, create_time").Where("id in (" + strings.Join(ids, ",") + ")").Find(&orderGoodsList)

	var amount float64
	for _, v := range orderGoodsList {
		amount += v["goods_price"].(float64) * float64(v["buy_number"].(int32))
		goodsData := service.GetShopGoods(int(v["goods_id"].(int32)))
		if goodsData.GoodsNumber < int(v["buy_number"].(int32)) {
			c.JSON(200, map[string]any{"status": 500, "msg": "商品库存不足：" + v["goods_name"].(string)})
			return
		}
	}

	if amount > userData.(model.User).Balance {
		c.JSON(200, map[string]any{"status": 500, "msg": "账户余额不足！"})
		return
	}

	dbEngine.Table("f_admin_user").Where("id=?", userData.(model.User).Id).Update(map[string]any{
		"balance": userData.(model.User).Balance - amount,
	})

	orderData := model.Order{
		UserId:      userData.(model.User).Id,
		OrderSn:     time.Now().Format("20060102150405") + "-" + utils.Strval(userData.(model.User).Id),
		OrderStatus: 1,
		OrderAmount: amount,
		Name:        userData.(model.User).Name,
		OrgName:     userData.(model.User).OrgName,
	}

	_, err := dbEngine.Table("f_shop_order").Insert(&orderData)
	fmt.Print(orderData.Id)
	msg := "添加成功"

	dbEngine.Table("f_shop_order_goods").Cols("id, goods_id, goods_name, goods_img, buy_number, sku_name, goods_price, selected, create_time").Where("id in (" + strings.Join(ids, ",") + ")").Update(map[string]any{
		"order_id":    orderData.Id,
		"user_name":   orderData.Name,
		"org_name":    orderData.OrgName,
		"create_time": time.Now().Format("2006-01-02 15:04:05"),
	})

	if err != nil {
		c.JSON(200, map[string]any{"status": 500, "msg": err.Error()})
	} else {
		c.JSON(200, map[string]any{"status": 200, "msg": msg})
	}
}

func UserCartDeleteCtrl(c *gin.Context) {
	param := GetJsonData(c)

	if param["id"] != nil {
		dbEngine.Table("f_shop_order_goods").Where("id in (?)", param["id"]).Delete()
		c.JSON(200, map[string]any{
			"status": 200,
			"msg":    "删除成功",
		})
	} else {
		c.JSON(200, map[string]any{
			"status": 200,
			"msg":    "参数错误",
		})
	}
}

func UserOrderIndexCtrl(c *gin.Context) {
	rowData := GetJsonData(c)
	if rowData == nil {
		rowData = map[string]any{
			"limit": 10.00,
			"page":  1.00,
		}
	}

	limit := int(rowData["limit"].(float64))
	start := (int(rowData["page"].(float64)) - 1) * limit

	if limit < 1 {
		limit = 10
	}

	dataArr := []model.Order{}
	dbEngine.Table("f_shop_order").Cols("id, name, org_name, order_amount, create_time").Limit(limit, start).Find(&dataArr)
	cnt, _ := dbEngine.Table("f_shop_order").Count()

	for index, item := range dataArr {
		items := []map[string]any{}
		dbEngine.Table("f_shop_order_goods").Cols("goods_id, goods_name, goods_img,goods_price, buy_number").Where("order_id=?", item.Id).Find(&items)

		item.OrderGoods = items
		dataArr[index] = item
	}

	c.JSON(200, ApiList{
		Status: 200,
		Data: ApiDataListObj{
			Total:   cnt,
			PerPage: limit,
			Data:    dataArr,
		},
	})
}
